import React, { forwardRef } from 'react'
import MaterialTable from 'material-table';
import AddBox from '@material-ui/icons/AddBox';
import ArrowUpward from '@material-ui/icons/ArrowUpward';
import Check from '@material-ui/icons/Check';
import ChevronRight from '@material-ui/icons/ChevronRight';
import Clear from '@material-ui/icons/Clear';
import DeleteOutline from '@material-ui/icons/DeleteOutline';
import Edit from '@material-ui/icons/Edit';
import FilterList from '@material-ui/icons/FilterList';
import Remove from '@material-ui/icons/Remove';
import SaveAlt from '@material-ui/icons/SaveAlt';
import Search from '@material-ui/icons/Search';
import ViewColumn from '@material-ui/icons/ViewColumn';
import { loc, loc_tag, is_empty } from 'sui';

const tableIcons = () => {
    return {
        Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
        Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
        Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
        Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
        DetailPanel: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
        Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
        Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
        Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
        FirstPage: forwardRef((props, ref) => <div className="text-base" {...props} ref={ref}>{loc("l_553")}</div>),
        LastPage: forwardRef((props, ref) =><div className="text-base" {...props} ref={ref}>{loc("l_556")}</div>),
        NextPage: forwardRef((props, ref) => <div className="text-base" {...props} ref={ref}>{loc("l_557")}</div>),
        PreviousPage: forwardRef((props, ref) => <div className="text-base" {...props} ref={ref}>{loc("l_558")}</div>),
        ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
        Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
        SortArrow: forwardRef((props, ref) => <ArrowUpward {...props} ref={ref} />),
        ThirdStateCheck: forwardRef((props, ref) => <Remove {...props} ref={ref} />),
        ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />)
    };
};

/* col: [
 *   {title: '序号', field: 'index'},
 *   {title: '工单号', field: 'sn', render: d => { return <div>xxxx</div> }},
 * ]
 *
 * row : [
 *   {index: '1', sn: "abc"},
 *   {index: '2', sn: "bcd"},
 * ]
 *
 * const editable = {
 *      onRowAdd: newData => new Promise((resolve, reject) => {
 *          setTimeout(() => {
 *              setRow([...row, newData]);
 *              resolve();
 *          }, 200);
 *      }),
 *      onRowUpdate: (newData, oldData) => new Promise((resolve, reject) => {
 *          setTimeout(() => {
 *              let data = [];
 *              data = row;
 *
 *              const f = data.find(d => d.sn === oldData.sn);
 *              if (f) {
 *                  f.sn = newData.sn;
 *                  f.des = newData.des;
 *              }
 *
 *              setRow(data);
 *              resolve();
 *          }, 200);
 *      }),
 *      onRowDelete: oldData => new Promise((resolve, reject) => {
 *          setTimeout(() => {
 *              let data = [];
 *              for (let i = 0; i < row.length; i++) {
 *                  let d = row[i];
 *                  if (d.sn === oldData.sn) {
 *                      continue;
 *                  }
 *
 *                  data.push(d);
 *              }
 *
 *              setRow(data);
 *              resolve();
 *          }, 200);
 *      }),
 *  };
 *
 *  hcsv: (columns, data) => {}
*/
const MaTable = ({
    col,
    row,
    hselect,
    hclick,
    hcsv,
    fn,
    detail,
    actions,
    exbt=true,
    paging=true,
    page=5,
    curpage=0,
    title="",
    opt={},
    search=true,
    sort=true,
    parent,
    pageopt=[5, 6, 7],
    editable,
}) => {
    if (is_empty(col)) {
        return null;
    }

    let filename = "export";
    if (fn) {
        filename = fn + "_" + loc_tag();
    }

    const hSelectionChange = (v) => {
        if (hselect) {
            hselect(v);
        }
    };

    const hRowClick = (e, v) => {
        if (hclick) {
            hclick(v);
        }
    };

    const expBt = () => {
        if (exbt) {
            return {
                csv: exbt,
                pdf: false,
            };
        }

        return false;
    };

    const getRow = () => {
        if (is_empty(row)) {
            return [];
        }

        return row;
    };

    return (
        <MaterialTable
            detailPanel={detail}
            icons={tableIcons()}
            title={title}
            localization={{
                pagination: {
                    labelDisplayedRows: `${loc("l_559")} {from}-{to} , ${loc("l_560")} {count}`,
                    labelRowsSelect: loc("l_125"),
                    firstAriaLabel: loc("l_561"),
                    firstTooltip: loc("l_561"),
                    previousAriaLabel: loc("l_558"),
                    previousTooltip: loc("l_558"),
                    nextAriaLabel: loc("l_557"),
                    nextTooltip: loc("l_557"),
                    lastAriaLabel: loc("l_564"),
                    lastTooltip: loc("l_564"),
                },
                body: {
                    emptyDataSourceMessage: "",
                    addTooltip: loc("l_239"),
                    deleteTooltip: loc("l_237"),
                    editTooltip: loc("l_496"),
                    editRow: {
                        deleteText: loc("l_554"),
                        cancelTooltip: loc("l_227"),
                        saveTooltip: loc("l_541"),
                    }
                },
                header: {
                    actions: "",
                },
                toolbar: {
                    searchTooltip: loc("l_593"),
                    searchPlaceholder: loc("l_593"),
                    exportTitle: loc("l_519"),
                    exportAriaLabel: loc("l_519"),
                    exportCSVName: loc("l_519") + " CSV",
                    nRowsSelected: `${loc("l_555")} {0} ${loc("l_125")}`,
                }
            }}
            options={{
                draggable: false,
                search: search,
                paging: paging,
                showTitle: title ? true : false,
                sorting: sort,
                exportAllData: true,
                exportButton: expBt(),
                exportFileName: filename,
                exportCsv: hcsv,
                pageSize: page,
                initialPage: curpage,
                pageSizeOptions: pageopt,
                ...opt
            }}
            onSelectionChange={hSelectionChange}
            onRowClick={hRowClick}
            columns={col}
            data={getRow()}
            actions={actions}
            parentChildData={parent}
            editable={editable}
        />
    );
};

export {MaTable};
